<template>
  <div class="search">
    <h1>区域管理</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>区域名称/编号</span>
    <el-input
      v-model="region_name"
      style="width: 200px; margin-right: 40%"
      placeholder="请输入"
    />
    <el-button type="primary" @click="searchVehicleRegions">查询</el-button>
    <el-button type="default" @click="reset">重置</el-button>
  </div>
  <!-- 区域列表 -->
  <div class="page">
    <div class="page-header">
      <div class="page-header-left">
        <span>区域列表</span>
      </div>
      <div class="page-header-right">
        <el-button
          type="primary"
          style="margin-top: 1rem"
          @click="to('car/newRegion')"
          >+&nbsp;新建
        </el-button>
        <el-button
          type="default"
          style="margin-top: 1rem; margin-right: 3rem"
          @click="deleteDialog = true"
          >批量删除</el-button
        >
        <el-dialog v-model="deleteDialog" title="警告" width="500" align-center>
          <span>是否删除选中的信息，该操作不可撤回！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialog = false">取消</el-button>
              <el-button type="primary" @click="deleteByIds"> 确认 </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column label="序号" prop="id" />
      <el-table-column label="区域名称" prop="name" />
      <el-table-column label="区域编号" prop="no" />
      <el-table-column label="区域面积" prop="area" />
      <el-table-column label="入库总数" prop="vehicleNum" />
      <el-table-column label="注释" prop="notes" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="editor(row.id)" type="text">编辑 </el-button>
          <el-button @click="deleteById(row.id)" type="text" size="small"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[20]"
        style="margin-bottom: 2rem"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElTable } from "element-plus";
import { reactive, ref } from "vue";
import to from "@/utils/to.js";
import axios from "axios";
import router from "@/router";

const loading = ref(false);
const deleteDialog = ref(false);
const selectRows = ref([]);

const pageSizeOptions = [20];

const tableData = ref([]);
const totalCount = ref(0);
const pageNum = ref(1);
const pageSize = ref(pageSizeOptions[0]);
const position_status = ref("");
const region_name = ref("");
const options = [
  { value: "", label: "全部" },
  { value: "审核中", label: "审核中" },
  { value: "审核通过", label: "审核通过" },
  { value: "审核不通过", label: "审核不通过" },
];

const form = reactive({
  id: "",
  no: "",
  owner: "",
  name: "",
  area: "",
  vehicleNum: "",
  notes: "",
});

const searchVehicleRegions = async () => {
  try {
    loading.value = true;
    const response = await axios.get(
      `http://localhost:8080/vehicleRegion/selectByName`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          name: region_name.value,
          status: position_status.value,
          regionName: region_name.value,
        },
      }
    );
    tableData.value = response.data.records;
    totalCount.value = response.data.total;
    loading.value = false;
  } catch (error) {
    console.error("查询区域列表失败:", error);
  }
};

//hhh
const reset = () => {
  region_name.value = ""; // 清空查询条件
  pageNum.value = 1; // 重置为第一页
  pageSize.value = pageSizeOptions[0]; // 重置每页条数为默认值
  searchVehicleRegions(); // 重新查询所有住户数据
};

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  searchVehicleRegions();
};

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  searchVehicleRegions();
};
// 初始化加载
searchVehicleRegions();

const editor = (id) => {
  router.push({ path: "/backend/car/newRegion", query: { id: id } });
};

const deleteById = async (id) => {
  console.log("Deleting region with id:", id); // 打印id值，确认id是否正确传递
  try {
    const response = await axios.delete(
      `http://localhost:8080/vehicleRegion/delete`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {
          id: id,
        },
      }
    );

    if (response.data.code === 1) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      searchVehicleRegions();
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage({
      message: "删除失败，请稍后再试",
      type: "error",
    });
  }
};

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/vehicleRegion/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map((item) => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        setTimeout(() => {
          searchVehicleRegions();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
